package com.suyuan.web;

import com.suyuan.entity.EmployeeInfo;
import com.suyuan.entity.Permission;
import com.suyuan.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证、授权Realm  --04-24
 */
public class AuthenticationRealm extends AuthorizingRealm {


    @Resource
    private EmployeeService employeeService;

    public void setName(String name){
       super.setName("AuthenticationRealm");
    }



    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
          EmployeeInfo curEmployeeInfo = (EmployeeInfo) principalCollection.getPrimaryPrincipal();
          SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
          List<Permission> permissionList = employeeService.getPermissions(curEmployeeInfo.getUsername());
          List<String> permissions = new ArrayList<String>();
          if(permissionList != null){
              for(Permission permission:permissionList){
                  //将数据库中的权限标签 符放入集合
                  permissions.add(permission.getPerCode());
              }
          }
          simpleAuthorizationInfo.addStringPermissions(permissions);
          return simpleAuthorizationInfo;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal(); // 获取用户名
        EmployeeInfo curEployee = employeeService.getByUsername(username);

        if(curEployee == null){
            throw new UnknownAccountException();//没找到帐号
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(curEployee,curEployee.getPassword(),this.getName());
        return simpleAuthenticationInfo;

    }

    //清除缓存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

}
